/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.OneCommerceProject.controllers.util;

import com.OneCommerceProject.beans.PhotosFacade;
import com.OneCommerceProject.entities.Photos;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Malek
 */
@ManagedBean
@RequestScoped
public class photosItemBean {

    private static StreamedContent defaultFileContent;
    private StreamedContent fileContent;
    @EJB
    private com.OneCommerceProject.beans.PhotosFacade ejbFacade;

    public StreamedContent getFileContent() throws FileNotFoundException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        String itemId = externalContext.getRequestParameterMap().get("item_id");

        if (itemId == null || itemId.equals("")) {
            fileContent = defaultFileContent;
        } else {
            int parsedId = Integer.parseInt(itemId);
            if (parsedId < 0) {
                fileContent = defaultFileContent;
            }
            List<Photos> listPhotos = ejbFacade.findByIdItem(itemId);
            String photoPath = listPhotos.get(0).getPhotopath().replaceAll("/", "\\");   
            System.out.println(System.getenv("USERPROFILE") + "\\Documents\\OneCommerceImages\\" + photoPath);
            StreamedContent content = new DefaultStreamedContent(new FileInputStream(System.getenv("USERPROFILE") + "\\Documents\\OneCommerceImages\\" + photoPath), "image/jpeg");
            return content;
        }
        return fileContent;
    }

    public void setFileContent(StreamedContent fileContent) {
        this.fileContent = fileContent;
    }

    static {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = contextClassLoader.getResourceAsStream("resources/images/Photo - 0.png");
        defaultFileContent = new DefaultStreamedContent(inputStream, "image/png");
    }


}
